package com.example.c5;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author Jonathan
 * 2021/5/30 0:13
 */
public class CloseFutureClient {
//    static final Logger log = Logger.getLogger(EventLoopClient.class);

    public static void main(String[] args) throws InterruptedException {
//        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap().group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        // 上面获取到的是一个异步的future
        channelFuture.sync();  // 上面是异步的  这个地方阻塞住当前线程
        Channel channel = channelFuture.channel();

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String s = scanner.nextLine();
                if ("q".equals(s)) {
                    channel.close(); // 异步关闭
                    break;
                }
                channel.writeAndFlush(s);
            }
        }, "input").start();
        ChannelFuture closeFuture = channel.closeFuture();
        System.out.println("waiting close");
        closeFuture.sync();
        System.out.println("关闭之后的操作");
        // 还可以加个异步回调函数
        // 优雅的关闭
        group.shutdownGracefully();

    }
}
